<template>
  <el-dialog v-model="visible" width="640px" append-to-body lock-scroll class="single-print-dialog">
    <template #header>
      <div class="header-strip">
        <div class="left">
          <el-icon>
            <Printer />
          </el-icon>
          <span>订单发货预览</span>
        </div>
        <!-- <el-tag size="small" type="info">单号 {{ order?.orderNo }}</el-tag> -->
      </div>
    </template>
    <div class="section-title remark-card">
      <span class="label">物流信息</span>
      <!-- 发货模式选择 (新增) -->
      <el-row :gutter="24">
        <el-col :span="8">
          <div class="mode-selector">
            <el-radio-group v-model="formData.shippingType">
              <el-radio-button
                v-for="item in logisticsTypeOptions"
                :label="item.value"
                :key="item.value"
                >{{ item.label }}</el-radio-button
              >
            </el-radio-group>
          </div>
        </el-col>
        <el-col :span="16">
          <div class="remark-row">
            <template v-if="formData.shippingType == '2'">
              <el-select
                v-model="formData.logisticsPlatformCode"
                placeholder="请选择物流公司"
                style="width: 150px"
                class="logistics-select"
              >
                <el-option
                  v-for="company in sysSelfFulfillmentOgistics"
                  :key="company.value"
                  :label="company.label"
                  :value="company.value"
                />
              </el-select>
              <el-input
                v-model="formData.logisticsNo"
                placeholder="输入物流单号"
                maxlength="20"
                show-word-limit
                style="width: 100%"
              />
            </template>

            <!-- 模式 2: 选择内定物流 -->
            <template v-else-if="formData.shippingType == '1'">
              <div></div>
              <div></div>
              <!-- 选择内定物流时，显示物流公司选择器 -->
              <el-select
                v-model="formData.logisticsPlatformCode"
                placeholder="请选择物流公司"
                style="width: 280px"
                class="logistics-select"
              >
                <el-option
                  v-for="company in logisticsCompany"
                  :key="company.value"
                  :label="company.label"
                  :value="company.value"
                />
              </el-select>
            </template>
          </div>
        </el-col>
      </el-row>
    </div>
    <div class="section-title order-card">
      <span class="label">订单信息</span>
      <div class="order-header">
        <div class="order-no">订单号：{{ order.orderNo }}</div>
        <div class="customer">
          <el-tag size="small" type="success">{{ order.receiverName }}</el-tag>
          <span class="phone">{{ order.receiverPhone }}</span>
        </div>
      </div>

      <el-divider />

      <div class="order-meta">
        <p><strong>下单时间：</strong>{{ order.orderTime }}</p>
        <p><strong>金额：</strong>¥{{ order.orderPrice?.toFixed(2) }}</p>
        <p><strong>收货地址：</strong>{{ order.receiverAddress }}</p>
      </div>

      <el-divider />

      <div class="remark">
        <el-icon class="editIcon">
          <ChatLineSquare />
        </el-icon>
        <div class="editCell">
          <EditableCell v-model="formData.remark" type="textarea" />
          <el-alert type="success" class="mt-10" :closable="false">
            打印备注：业务员自己定义的模板-实付金额-商品1数量-商品2数量 可以编辑
          </el-alert>
        </div>
      </div>
    </div>

    <!-- Footer -->
    <template #footer>
      <div class="footer-bar">
        <el-button @click="close">取消</el-button>
        <el-button
          v-if="formData.shippingType === '1'"
          type="primary"
          :icon="Printer"
          @click="print"
        >
          确认打印
        </el-button>
        <el-button v-else type="success" :icon="Van" @click="print"> 确认发货 </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { ref, nextTick, reactive, watch } from 'vue';
import { Printer, ChatLineSquare, Van } from '@element-plus/icons-vue';
import { ElMessage } from 'element-plus';
import { logisticsShipping } from '../../api/platformOrders/orders/list';
import useUserStore from '../../store/modules/user';
const userApp = useUserStore();

interface Option {
  value?: any;
  label?: string;
  [key: string]: any;
}

const props = withDefaults(
  defineProps<{
    logisticsCompany?: Option[];
    payType?: Option[];
    logisticsTypeOptions?: Option[];
    sysSelfFulfillmentOgistics?: Option[];
  }>(),
  {
    // 物流公司
    logisticsCompany: () => [],
    payType: () => [],
    logisticsTypeOptions: () => [],
    sysSelfFulfillmentOgistics: () => []
  }
);

const visible = ref(false);
const order = ref<any>(null);
const formData = reactive({
  // 发货类型
  shippingType: '1',
  // 系统发货
  logisticsPlatformCode: '', // 物流公司id
  logisticsNo: '', // 物流单号
  remark: '' // 打印备注
});

// 切换物流类型 清空 物流和单号
watch(
  () => formData.shippingType,
  () => {
    formData.logisticsPlatformCode = '';
    formData.logisticsNo = '';
  }
);

// 事件
const emits = defineEmits(['ok']);

// methods
const show = async (data: any) => {
  order.value = { ...data };
  visible.value = true;
  await nextTick();
};

const close = () => {
  visible.value = false;
};

watch(
  [() => userApp.printStr, () => order.value],
  ([newStr, newOrder]) => {
    if (newOrder) {
      // // newStr + 订单金额 + 商品1数量 + 商品2数量
      let shopStr = newStr + '-';
      shopStr += `实付金额：${newOrder.actualPrice?.toFixed(2)}元 - `;
      newOrder.productCollection.forEach((item: any) => {
        if (!item.num) return;
        shopStr += `商品${item.productName}【${item.typeValue}】${item.num}件 - `;
      });
      formData.remark = shopStr;
    }
  },
  {
    deep: true
    // immediate: true,
  }
);

// 打印发货
const print = () => {
  const args = {
    orderId: order.value.orderId,
    remark: formData.remark,
    shippingType: formData.shippingType,
    logisticsNo: formData.logisticsNo,
    logisticsPlatformCode: formData.logisticsPlatformCode
  };
  // 物流公司必填
  if (!args.logisticsPlatformCode) {
    ElMessage.error('请选择物流公司');
    return;
  }
  //如果是自主发货，单号必填
  if (args.shippingType === '2') {
    if (!args.logisticsNo) {
      ElMessage.error('请输入物流单号');
      return;
    }
  }
  logisticsShipping(args).then((res) => {
    if (res.code === 200) {
      ElMessage.success('发货成功');
      close();
      emits('ok');
    }
  });
};

defineExpose({ show, close });
</script>

<style lang="scss" scoped>
.single-print-dialog :deep(.el-dialog__header) {
  display: none;
}

.header-strip {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 0 12px 0;
  font-size: 15px;
  font-weight: 600;
  color: #333;

  .left {
    display: flex;
    align-items: center;
    gap: 8px;
  }
}

.section-title {
  border: 1px solid #ebebeb;
  padding: 40px 20px 20px 20px;
  box-sizing: border-box;
  border-radius: 4px;
  position: relative;
  margin-bottom: 10px;

  .label {
    position: absolute;
    display: inline-block;
    padding: 5px 10px;
    background: #ebebeb;
    font-size: 13px;
    margin-bottom: 10px;
    border-radius: 0 4px 4px 0;
    left: 0;
    top: 0;
  }
}

.remark-card {
  display: flex;
  align-items: center;

  .mode-selector {
    margin-right: 10px;
    width: 180px;
  }

  .remark-row {
    display: flex;
    align-items: center;
    gap: 10px;
    width: 100%;
  }
}

.order-card {
  border-radius: 4px;
  font-size: 14px;
  color: #444;

  .order-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  .order-no {
    font-weight: 600;
    font-size: 15px;
  }

  .customer {
    display: flex;
    align-items: center;
    gap: 6px;
    color: #555;
  }

  .order-meta {
    font-size: 13px;
    line-height: 1.6;
  }

  .remark {
    display: flex;
    align-items: flex-start;
    gap: 6px;
    color: #333;
    font-size: 14px;

    .editIcon {
      margin-top: 6px;
    }

    .editCell {
      width: 100%;
    }
  }
}

.footer-bar {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}
</style>
